function getMenuAppIcon(icns, size)
    icns = icns or commonIcon
    size = size or commonSize
    return hs.image.imageFromPath('~/.hammerspoon/icns/' .. icns):setSize(size)
end

caffeine = hs.menubar.new()
caffeine:setTitle('常用')
caffeine:setIcon(getMenuAppIcon('folder_05.icns'):setSize({h = 22, w = 22}))

function generateMenuItem(menu,name, itemConfig)
    if name:sub(1,2) == '__' then return end
    local item = {title = name, image = getMenuAppIcon(itemConfig['icon'] or commonIcon, itemConfig['iconSize']or commonSize)}
    local fnlist = {}
    for key, value in pairs(itemConfig) do
        if key== 'openApp' then
            table.insert(fnlist, openApp(value))
        end

        if key == 'openEdgeApp' then
            table.insert(fnlist, openEdgeApp(value))
        end

        if key == 'openInFinder' then
            table.insert(fnlist, explore(value))
        end

        if key == 'openWithApp' and itemConfig['useApp'] then
            table.insert(fnlist, openWithTargetApp(value,itemConfig['useApp']))
        end

        if key =='openWeb' then
            table.insert(fnlist, openWeb(value, itemConfig['useBrower']))
        elseif key =='openWebList' then
            table.insert(fnlist, openWebList(value, itemConfig['useBrower']))
        end

        if key == 'cmd' then
            table.insert(fnlist, execute(value))
        end

        if key == 'subMenu' then
            item.menu = {};
            generateMenuItemArray(item.menu,value)
        end
    end
    item.fn = function()
        for _, v in ipairs(fnlist) do
            v()
        end
    end

    table.insert(menu, item)
end

function generateActivityMenuItem(slotMenu,name,config)
    local doc = config["doc"]
    local resGroupPath = config["resGroup"]
    local resName = config["resName"]
    local resGroupPath = config["resGroupPath"] or "~/work/WorldTourCasinoResource/"
    local item = {
                title = name,
                image = getMenuAppIcon('ccdoc.icns'):setSize(commonSize),
                fn = openWeb(doc),
                menu = {
                    {
                        title = "拷贝资源名",
                        image = getMenuAppIcon('Terminal.icns'):setSize({w=22,h=22}),
                        fn = execute("echo "..resName .." |pbcopy")
                    }
                }
            }
    table.insert(slotMenu,item)
end

function generateSlotMenuItem(slotMenu,name,config)
    local doc = config["doc"]
    local resGroup = config["resGroup"]
    local resName = config["resName"]
    local resGroupPath = config["resGroupPath"] or "~/work/WorldTourCasinoResource/theme"..resGroup
    local ccbproj = resGroupPath .. '/theme' .. resGroup .. '.ccbproj'
    local resPath = resGroupPath .. '/Resources/' .. resName
    local item = {
                title = name,
                fn = openWithTargetApp(ccbproj, 'CocosBuilder'),
                image = getMenuAppIcon('CocosBuilderDocIcon.icns'):setSize(commonSize),
                menu = {
                    {
                        title = "文档",
                        image = getMenuAppIcon('ccdoc.icns'):setSize({w=22,h=22}),
                        fn = openWeb(doc)
                    },{
                        title = "打开资源目录",
                        image = getMenuAppIcon('folder_03.icns'):setSize({w=22,h=22}),
                        fn = explore(resPath)
                    },{
                        title = "拷贝路径",
                        image = getMenuAppIcon('Terminal.icns'):setSize({w=22,h=22}),
                        fn = execute("echo "..resPath .." |pbcopy")
                    },
                    {
                        title = "拷贝资源名",
                        image = getMenuAppIcon('Terminal.icns'):setSize({w=22,h=22}),
                        fn = execute("echo "..resName .." |pbcopy")
                    },
                }
            }
    table.insert(slotMenu,item)
end

function generateMenuItemArray(menu, itemConfigs,__needCuteLine__)
    if __needCuteLine__ == nil then
        __needCuteLine__ = true;
    end
    local numList = {};
    for name, config in pairs(itemConfigs) do
        if tonumber(name) ~= nil then
            table.insert(numList,tonumber(name));
        end
    end
    table.sort(numList);
    for i = 1,#numList do
            generateMenuItemArray(menu, itemConfigs[tostring(numList[i])],itemConfigs[tostring(numList[i])].__needCuteLine__)
    end

    for name, config in pairs(itemConfigs) do
        if tonumber(name) == nil then
            generateMenuItem(menu, name, config)
        end
    end


    if __needCuteLine__  then
        table.insert(menu, {title = '-'})
    end
end

local mainMenu = {}
local file = io.open('config.json', 'r')
local content = file:read('*a')
file:close()

local menuConfig = hs.json.decode(content)
local activityMenuConfig = menuConfig["活动"]
menuConfig["活动"] = nil
local slotMenuConfig = menuConfig["关卡"]
menuConfig["关卡"] = nil
local ProfileMenuConfig = menuConfig['环境配置']
menuConfig['环境配置'] = nil

generateMenuItemArray(mainMenu, menuConfig,false)

if activityMenuConfig ~= nil then
    local activityMenu = {
        title = "活动",
        image = getMenuAppIcon('ccdoc.icns'):setSize({h = 26, w = 26}),
        menu = {}
    }
    for activityName, activityConfig in pairs(activityMenuConfig) do
        generateActivityMenuItem(activityMenu.menu, activityName, activityConfig)
    end
    table.insert(mainMenu, activityMenu)
end

if slotMenuConfig ~= nil then
    local slotMenu = {
        title = "关卡",
        image = getMenuAppIcon('CocosBuilderProjectIcon.icns'):setSize({h = 26, w = 26}),
        menu = {},
        fn = cmdWithInput('python ~/work/WorldTourCasinoResource/openSubjectCCB.py','输入关卡 id ,打开关卡 CCB 工程'),
    }
    for slotName, slotConfig in pairs(slotMenuConfig) do
        generateSlotMenuItem(slotMenu.menu, slotName, slotConfig)
    end
    table.insert(mainMenu, slotMenu)
end

if ProfileMenuConfig ~= nil then
    table.insert(mainMenu, {title = '-'})
   generateMenuItemArray(mainMenu, ProfileMenuConfig, false)
end

local settingMenu = {
    {title = '-'},
    {
        title = 'Hammerspoon',
        fn = openWithVscode('~/.hammerspoon'),
        image = getMenuAppIcon('hammerspoon.icns'):setSize({h = 26, w = 26}),
        menu = {
            {
                title = 'hs-doc',
                fn = openWeb('https://www.hammerspoon.org/docs/index.html'),
                image = getMenuAppIcon('ccdoc.icns'):setSize({h = 26, w = 26})
            },
            {
                title = 'hs-path',
                fn = explore('~/.hammerspoon'),
                image = getMenuAppIcon('AppIcon.icns'):setSize({h = 26, w = 26})
            },
            {
                title = 'hs-console',
                fn = openApp('Hammerspoon.app'),
                image = getMenuAppIcon('hammerspoon.icns'):setSize({h = 26, w = 26})
            }
        }
    },
    {
        title = 'hs-reload',
        fn = function()
            hs.reload()
        end,
        image = getMenuAppIcon('hammerspoon.icns'):setSize({h = 26, w = 26})
    },
    {
        title = 'openTerminal',
        fn = function()
            openTerminalInCurrentFinderDir()
        end,
        image = getMenuAppIcon('hammerspoon.icns'):setSize({h = 26, w = 26})
    }
}
for k, v in ipairs(settingMenu) do
    table.insert(mainMenu, v)
end

caffeine:setMenu(mainMenu)